package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class SkyTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 通过定时任务每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单），
     * 如果存在则修改订单状态为“已取消”
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processOrder4Timeout(){
        log.info("processOrder4Timeout...");

        // select * from orders where status = 1 and order_time < (当前时间 - 15分钟)
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);

        List<Orders> ordersList = orderMapper.getListByCondition(Orders.PENDING_PAYMENT, time);
        if(ordersList != null && ordersList.size() > 0){
            for(Orders orders : ordersList){
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 通过定时任务每天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processOrder4Delivery(){
        log.info("processOrder4Delivery...");

        // 凌晨1点，查找0点之前的订单（昨天之前的订单）
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);

        List<Orders> ordersList = orderMapper.getListByCondition(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList != null && ordersList.size() > 0){
            for(Orders orders : ordersList){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
